<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="流程名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入流程名"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程key" prop="key">
        <el-input
          v-model="queryParams.key"
          placeholder="请输入流程key"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label="开始时间">
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="开始时间"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :picker-options="startDatePicker"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="结束时间"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :picker-options="endDatePicker"
        >
        </el-date-picker>
      </el-form-item>
      -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['category:add']"
        >新增
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['category:del']"
        >删除
        </el-button>
      </el-col>
      -->
      <el-col :span="1.5">
        <el-upload
          action=""
          :http-request="uploadFile"
          accept=".bpmn"
          ref='upload'
          :file-list="fileList"
          :limit="1">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-upload2"
          >导入流程
          </el-button>
        </el-upload>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="60" align="center"/>
      <el-table-column prop="id" label="流程ID" :show-overflow-tooltip="true" align="center"></el-table-column>
      <el-table-column prop="key" label="流程KEY" :show-overflow-tooltip="true" align="center"></el-table-column>
      <el-table-column prop="name" label="流程名称" :show-overflow-tooltip="true" align="center"></el-table-column>
      <el-table-column prop="version" label="版本" :show-overflow-tooltip="true" align="center"></el-table-column>
      <el-table-column prop="deploymentId" label="部署ID" :show-overflow-tooltip="true" align="center"></el-table-column>
      <el-table-column prop="deploymentTime" label="部署时间" :show-overflow-tooltip="true" align="center"></el-table-column>
      <el-table-column label="状态" prop="suspendState">
        <template slot-scope="scope">
          <el-col v-if="scope.row.suspendState==0">激活</el-col>
          <el-col v-if="scope.row.suspendState==1">挂起</el-col>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleView(scope.row)"
                     v-hasPermi="['definition:view']"
          >查看流程
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="suspendOrActive(scope.row)"
            v-hasPermi="['definition:update']"
          >{{scope.row.suspendState==0?'挂起':'激活'}}
          </el-button>
          <!--
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['category:del']"
          >删除
          </el-button>
          -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
     <!--bpmnjs在线流程设计器-->
    <el-dialog
      :visible.sync="modelVisible"
      title="流程图"
      width="1680px"
      @close="modelCancel"
      append-to-body
    >
      <div style="position:relative;height: 100%;">
        <iframe
          id="iframe"
          :src="modelerUrl"
          frameborder="0"
          width="100%"
          height="720px"
          scrolling="auto"
        ></iframe>
      </div>
    </el-dialog>
    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品类别" prop="categoryKey">
              <el-input v-model="form.categoryKey" placeholder="请输入产品类别"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="产品编码" prop="categoryCode">
              <el-input v-model="form.categoryCode" placeholder="请输入产品编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类别名称" prop="categoryName">
              <el-input v-model="form.categoryName" placeholder="请输入产品类别名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="产品别名" prop="aliasName">
              <el-input v-model="form.aliasName" placeholder="请输入产品别名"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {importProcess,queryList,suspendDefinition,deleteDefinition} from "@/api/activiti/groups";
  import {deepClone} from "@/utils/index";
  import { getToken } from '@/utils/auth'

  export default {
    name: "flowDefinition",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        modelVisible: false,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 表格树数据
        list: [],
        //文件列表
        fileList: [],
        modelerUrl: "",
        // 菜单树选项
        menuOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageNo: 1,
          pageSize: 10,
          startTime: '',
          endTime: '',
          name: '',
          key: ''
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          categoryKey: [
            {required: true, message: "产品类别不能为空", trigger: "blur"}
          ],
          // categoryCode: [
          //   {required: true, message: "产品编码不能为空", trigger: "blur"}
          // ],
          categoryName: [
            {required: true, message: "产品类别名称不能为空", trigger: "blur"}
          ]
        },
        startDatePicker: this.beginDate(),
        endDatePicker: this.processDate()
      };
    },
    created() {
      this.getList();
    },
    watch:{
      total(val,oldVal){
        /*  第N页最后一条数据删除后 重新加载上一页 */
        if(this.total>0 && this.total%this.queryParams.pageSize === 0){
          this.queryParams.pageNo = this.queryParams.pageNo - 1
          this.getList(this.queryParams)
        }
      }
    },
    methods: {
      beginDate(){
            return {
                disabledDate: time =>{
                if (this.endTime) {
                   return new Date(this.endTime).getTime()> time.getTime()
                    
                } else {
                    return time.getTime() > Date.now()
                }
                }
            }
      },
      processDate() {
            return {
                disabledDate: time =>{
                if (this.startTime) {
                    return new Date(this.startTime).getTime() < time.getTime()
                        
                } else {
                    return time.getTime() > Date.now()
                }
                }
            }
      },
      getList() {
        this.loading = true;
        queryList(this.queryParams).then(response => {
          this.list = response.data;
          this.total = response.page.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          categoryKey: '',
          categoryName: '',
          aliasName: ''
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNo = 1
        this.getList();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.form.id = '';
        this.open = true;
        this.title = "添加任务";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.form = deepClone(row);
        this.open = true;
        this.title = "修改任务";
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id !== '') {
              updateTask(this.form).then(response => {
                if (response.code === 0) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addTask(this.form).then(response => {
                if (response.code === 0) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        let dictIds = [];
        if (row.deploymentId) {
          dictIds.push(row.deploymentId);
        } else {
          dictIds = this.ids
        }
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return deleteDefinition({'ids' : dictIds});
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
       /** 导入流程操作 */
      handleGroupsAdd() {
        this.reset();
        this.form.id = '';
        this.open = true;
        this.title = "导入流程";
      },
      uploadFile(upload){
                
        let reader = new FileReader()
        reader.readAsDataURL(upload.file)
        var fileName = upload.file.name;
        var data = {};
        var that = this
        reader.onload = ()=>{

          data = {"file":reader.result,"fileName":fileName};
          //上传
          that.uploading = true
          importProcess(data).then(function(response){
              console.log(response)
              if(response.code === 0){
                //上传成功处理
                that.$message.success("上传成功")
                that.uploading = false
                that.$refs.upload.clearFiles()
                that.getList()
              }
          },err=>{
              that.uploading = false
          })
        }
      },
      suspendOrActive(row) {
        var suspendOrActive = row.suspendState == '2' ? '激活' : '挂起';
        this.$confirm('确认要' + suspendOrActive + '流程定义吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          var data = {"definitionId": row.id, "state": row.suspendState=='0'?'1':'0'};
          return suspendDefinition(data);
        }).then(() => {
          this.getList();
          this.msgSuccess(suspendOrActive.concat("成功"));
        }).catch(function () {
        });
      },
      handleView(row) {
        this.modelVisible = true;
        console.info(row.deploymentId)
        console.info(row.resourceName)
        localStorage.setItem("token",getToken())
        localStorage.setItem("basePath",process.env.VUE_APP_BASE_API_URL)
        this.modelerUrl = '/bpmnjs/index.html?type=lookBpmn&deploymentFileUUID=' + row.deploymentId + '&deploymentName=' + encodeURI(row.resourceName);
      },
      modelCancel() {
        this.getList();
      }
    }
  };
</script>
